package com.dex4d.core;

import android.os.Bundle;
import android.view.View;

import com.framework.R;
import com.gyf.barlibrary.ImmersionBar;
import com.kymjs.frame.presenter.FragmentPresenter;
import com.kymjs.frame.view.IDelegate;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Created by chengyuchun on 2017/3/7.
 */
public abstract class BaseFragmentPresenter<T extends IDelegate> extends FragmentPresenter<T> {

    protected boolean isVisibleToUser;
    protected boolean isViewInitialized;
    protected boolean isDataInitialized;
    protected boolean isLazyLoadEnabled;
    protected ImmersionBar mImmersionBar;
    protected Unbinder mUnbinder;

    protected  void loadData(){};

    public void enableLazyLoad(){
        isLazyLoadEnabled = true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        checkIfLoadData();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mUnbinder = ButterKnife.bind(this,view);
        initImmersionBar();
        if (!isLazyLoadEnabled){
            loadData();
        }else {
            isViewInitialized = true;
            if (savedInstanceState != null){
                onRestoreInstanceState(savedInstanceState);
            }
            checkIfLoadData();
        }
    }

    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        isDataInitialized = true;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isViewInitialized = false;
    }

    protected void checkIfLoadData() {
        if (isVisibleToUser && isViewInitialized ) {
            isDataInitialized = true;
//            TODO load data
            loadData();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && mImmersionBar != null)
            mImmersionBar.fullScreen(false).navigationBarColor(R.color.black);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null)
            mImmersionBar.destroy();
        if (mUnbinder != null)
            mUnbinder.unbind();//解绑View
    }

    /**
     * 初始化沉浸式
     */
    protected void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.keyboardEnable(true).navigationBarWithKitkatEnable(false).init();
    }

}
